"use client"

import { useState, useRef, useEffect } from "react"
import "./ChatModal.css"

function ChatModal() {
  const [messages, setMessages] = useState([])
  const [inputValue, setInputValue] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState(null)
  const messagesEndRef = useRef(null)
  const inputRef = useRef(null)

  // 自动滚动到最新消息
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
  }

  const getAuthHeaders = () => {
    const token = localStorage.getItem("token")
    return {
      Authorization: token ? `Bearer ${token}` : "",
      "Content-Type": "application/json",
    }
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  // 聚焦输入框
  useEffect(() => {
    inputRef.current?.focus()
  }, [])

  // 处理输入变化
  const handleInputChange = (e) => {
    setInputValue(e.target.value)
  }

  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!inputValue.trim()) return;

    const userMessage = inputValue.trim();
    setInputValue("");

    // 添加用户消息到聊天记录
    setMessages((prev) => [
      ...prev,
      { 
        role: "user", 
        content: userMessage, 
        timestamp: new Date() 
      }
    ]);

    setIsLoading(true);
    setError(null);

    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 15000); // 15秒超时

      const response = await fetch("/api/assistant/chat", {
        method: "POST",
        headers: {
          ...getAuthHeaders(),
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ userMessage }),
        signal: controller.signal
      });

      clearTimeout(timeoutId);

      // 检查响应状态
      if (!response.ok) {
        const errorText = await response.text();
        let errorMsg = `请求失败: ${response.status}`;
        
        try {
          const errorJson = JSON.parse(errorText);
          errorMsg = errorJson.message || errorMsg;
        } catch {}
        
        throw new Error(errorMsg);
      }

      // 检查内容类型并解析响应
      const contentType = response.headers.get('content-type') || '';
      let responseData;
      
      const textData = await response.text();
      responseData = { response: textData };

      // 添加AI回复到聊天记录
      setMessages((prev) => [
        ...prev,
        { 
          role: "assistant", 
          content: responseData.response || responseData.message || "抱歉，我无法回答这个问题。",
          timestamp: new Date(),
          data: responseData // 保留完整响应数据
        }
      ]);

    } catch (err) {
      console.error("聊天请求错误:", err);
      
      const errorMessage = 
        err.name === 'AbortError' ? "请求超时，请稍后重试" :
        err.message.includes('Failed to fetch') ? "网络连接失败" :
        err.message;

      setError(errorMessage);

      // 添加错误消息到聊天记录
      setMessages((prev) => [
        ...prev,
        {
          role: "system",
          content: `错误: ${errorMessage}`,
          timestamp: new Date(),
          isError: true
        }
      ]);

    } finally {
      setIsLoading(false);
    }
  };

  // 格式化时间
  const formatTime = (date) => {
    return new Date(date).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
  }

  // 处理重试
  const handleRetry = () => {
    if (messages.length >= 1) {
      const lastUserMessage = messages.filter((msg) => msg.role === "user").pop()
      if (lastUserMessage) {
        handleSubmitMessage(lastUserMessage.content)
      }
    }
  }

  // 提交消息的函数（不通过表单）
  const handleSubmitMessage = async (message) => {
    if (!message.trim()) return;

    // 添加用户消息到聊天记录
    setMessages((prev) => [
      ...prev,
      { role: "user", content: message, timestamp: new Date() }
    ]);

    setIsLoading(true);
    setError(null);

    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 15000); // 15秒超时

      const response = await fetch("/api/assistant/chat", {
        method: "POST",
        headers: {
          ...getAuthHeaders(),
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ userMessage: message }),
      });

      clearTimeout(timeoutId);

      if (!response.ok) {
        const errorText = await response.text();
        let errorMsg = `请求失败: ${response.status}`;
        
        try {
          const errorJson = JSON.parse(errorText);
          errorMsg = errorJson.message || errorMsg;
        } catch {}
        
        throw new Error(errorMsg);
      }

      // 检查内容类型并解析响应
      const contentType = response.headers.get('content-type') || '';
      let responseData;

      const textData = await response.text();
      responseData = { response: textData }; // 将纯文本包装为对象

      // 添加AI回复到聊天记录
      setMessages((prev) => [
        ...prev,
        { 
          role: "assistant", 
          content: responseData.response || responseData.message || "抱歉，我无法回答这个问题。",
          timestamp: new Date(),
          rawData: responseData // 保留原始响应数据
        }
      ]);

    } catch (err) {
      console.error("聊天请求错误:", err);
      
      const errorMessage = 
        err.name === 'AbortError' ? "请求超时，请稍后重试" :
        err.message.includes('Failed to fetch') ? "网络连接失败" :
        err.message;

      setError(errorMessage);

      // 添加错误消息到聊天记录
      setMessages((prev) => [
        ...prev,
        {
          role: "system",
          content: `错误: ${errorMessage}`,
          timestamp: new Date(),
          isError: true
        }
      ]);

    } finally {
      setIsLoading(false);
    }
  };

  // 清空聊天记录
  const handleClearChat = () => {
    if (window.confirm("确定要清空所有聊天记录吗？")) {
      setMessages([])
    }
  }

  return (
    <div className="chat-container">

      <div className="messages-container">
        {messages.length === 0 ? (
          <div className="welcome-message">
            <h2>欢迎使用AI助手</h2>
            <p>您可以向我提问任何问题，我会尽力回答。</p>
            <div className="example-questions">
              <h3>示例问题：</h3>
              <button className="example-question-button" onClick={() => handleSubmitMessage("增量卡有什么用？")}>
                增量卡有什么用？
              </button>
              <button className="example-question-button" onClick={() => handleSubmitMessage("如何提高上传量？")}>
                如何提高上传量？
              </button>
              <button className="example-question-button" onClick={() => handleSubmitMessage("如何使用邀请码？")}>
                如何使用邀请码？
              </button>
            </div>
          </div>
        ) : (
          messages.map((message, index) => (
            <div key={index} className={`message ${message.role} ${message.isError ? "error" : ""}`}>
              <div className="message-avatar">
                {message.role === "user" ? "👤" : message.role === "assistant" ? "🤖" : "⚠️"}
              </div>
              <div className="message-content">
                <div className="message-header">
                  <span className="message-sender">
                    {message.role === "user" ? "您" : message.role === "assistant" ? "AI助手" : "系统"}
                  </span>
                  <span className="message-time">{formatTime(message.timestamp)}</span>
                </div>
                <div className="message-text">{message.content}</div>
              </div>
            </div>
          ))
        )}

        {isLoading && (
          <div className="message assistant loading">
            <div className="message-avatar">🤖</div>
            <div className="message-content">
              <div className="message-header">
                <span className="message-sender">AI助手</span>
                <span className="message-time">{formatTime(new Date())}</span>
              </div>
              <div className="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      <form className="input-form" onSubmit={handleSubmit}>
        <div className="input-container">
          <input
            ref={inputRef}
            type="text"
            value={inputValue}
            onChange={handleInputChange}
            placeholder="输入您的问题..."
            disabled={isLoading}
            className="message-input"
          />
          <button type="submit" disabled={isLoading || !inputValue.trim()} className="send-button">
            {isLoading ? "发送中..." : "发送"}
          </button>
        </div>

        {error && <div className="error-message">{error}</div>}

      </form>
    </div>
  )
}

export default ChatModal
